package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.dtos.WmUserDto;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.pojos.AdUser;
import com.heima.model.common.pojos.WmUser;
import com.heima.utils.common.AppJwtUtil;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
@Transactional//开启事务
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {

    //登录方法
    @Override
    public ResponseResult longin(WmUserDto dto) {
        //判断参数
        if(StringUtils.isBlank(dto.getName())|| StringUtils.isBlank(dto.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户名或者密码不能为空");
        }
        //通过用户名查询
        WmUser wmUser = getOne(Wrappers.<WmUser>lambdaQuery().eq(WmUser::getName, dto.getName()));
        if(wmUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户名不能正确");
        }else{
            //获得salt盐
            String salt = wmUser.getSalt();
            //获得用户输入的密码
            String password=dto.getPassword();
            //通过工具类生产密码
            String pswd = DigestUtils.md5DigestAsHex((password + salt).getBytes());
            //判断密码是否正确
            if(pswd.equals(wmUser.getPassword())){
                //生产Jwt返回前端
                Map<String,Object> map = new HashMap<>();
                //通过工具类 生产Jwt
                map.put("token", AppJwtUtil.getToken(wmUser.getId().longValue()));
                wmUser.setPassword("");
                wmUser.setSalt("");
                map.put("user",wmUser);
                return ResponseResult.okResult(map);

            }else {
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }

        }

    }
}
